#include "Enemy.h"
#include "Player.h"
#include "LABEL.h"
#include "EnemyWave.h"

const char* Enemy::ENEMY_MODEL_PATH = "media/models/mask/mask.md2";
const Array Enemy::ENEMY_INICIAL_POSITION = Array(10,0,-30);
const double Enemy::VELOCIDADE_PULO = 70.0;
int Enemy::vidaInicial;
int numeroVezesNaMesmaPosicao;
Array ultimaPosicao;

Enemy::Enemy(int life,double speed, int strength)
{
    vida = life;
    velocidade = speed;
    forca = strength;
    numeroVezesNaMesmaPosicao = 0;
    ultimaPosicao = Enemy::ENEMY_INICIAL_POSITION;
    init();
}

void Enemy::init()
{
    load(Enemy::ENEMY_MODEL_PATH);
    label(LABEL::ENEMY);

    graphic().setAnimationDelay(Animation::WALK,10);
    graphic().setAnimationDelay(Animation::HIT02,6);
    graphic().setAnimationDelay(Animation::DIE01,12);

    changeAnimation(Animation::WALK);
    changeBoundingVolume(Solid::OBOX);
    animatedVolume();

    hide();
}

void Enemy::act()
{
    if (died())
    {
        hide();
    }
}

int Enemy::collide(Object &other)
{

    switch(other.label())
    {
        case LABEL::PARTICLE:
            vida --;
            if(vida <= 0)
            {
                SoundSource::dieSound.play();
                inactiveBody();
                tempAnimation(Animation::HIT02,Animation::DIE01);
                Player::pontos += getPoints();
                EnemyWave::numeroInimigosVivos--;
                if(EnemyWave::numeroInimigosVivos <= 0)
                {
                    SoundSource::playNewWave = true;
                }
            }
            else
            {
                SoundSource::painSound.play();
                changeAnimation(Animation::HIT02);
            }
            break;
        default:
            break;
    }
    return 1;
}

void Enemy::appear()
{
    visible(true);
    activeBody();
}

void Enemy::hide()
{
    visible(false);
    inactiveBody();
    position(Enemy::ENEMY_INICIAL_POSITION);
}

bool Enemy::died()
{
    return ((vida<=0) && (graphic().isAnimationOver()));
}

int Enemy::getPoints()
{
    return forca*(vidaInicial + velocidade);
}

bool Enemy::needJump()
{
    bool precisaPular = false;

    if ((round(position().getx()) == round(ultimaPosicao.getx())) &&
       (round(position().gety()) == round(ultimaPosicao.gety())) &&
       (round(position().getz()) == round(ultimaPosicao.getz())))
    {
        numeroVezesNaMesmaPosicao++;
    }
    else
    {
        numeroVezesNaMesmaPosicao = 0;
        ultimaPosicao = position();
    }

    if (numeroVezesNaMesmaPosicao >= 50)
    {
        precisaPular = true;
        numeroVezesNaMesmaPosicao = 0;
    }
    return precisaPular;
}

void Enemy::jump()
{
    if(vida > 0)
    {
        changeAnimation(Animation::JUMP);
        velocity(0.0,Enemy::VELOCIDADE_PULO,0.0);
    }
}
